/**   
 * @Title: UsersService.java
 * @Package com.wx
 * @Description: 
 * @author wangxiao
 * @date 2017年11月7日 下午2:24:31
 */
package com.wx.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wx.model.WxShop;
import com.wx.util.LocationUtils;
import com.xiaoleilu.hutool.json.JSONArray;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**   
 * @ClassName: UsersService
 * @Description: 
 * @author wangxiao
 * @date 2017年11月7日 下午2:24:31
 */
public class ShopService {
	public static final ShopService me = new ShopService();
	private final WxShop shopDao = new WxShop().dao();
	
    private static String GET_XY_FORM = "http://apis.map.qq.com/ws/distance/v1/?mode=driving&from=【FROM】&to=【TO】&key=【KEY】";
    
    private static String GET_ADD_XY = "http://apis.map.qq.com/ws/geocoder/v1/?address=【ADD】&output=json&key=【KEY】";
	
	private static String GET_XY_FORM_KEY ="WPDBZ-DX3CD-WEY4I-HH5Z6-TP2VZ-6CBPX";
	
	public List<Record> getAllWxShop(int account_id){
		List<Record> wxList = Db.find("select * from WX_SHOP w where w.account_id = ?",account_id);
		return wxList;
	}
	
	
	public List<Record> getWxShopListAndTag(int account_id,double lng,double lat){
		List<Record> wxList = ShopService.me.getAllWxShop(account_id);
		List<Record> retList = new ArrayList<>();
		if(wxList.size()>0){
			for(int i =0;i<wxList.size();i++){
				if(!StrUtil.isEmpty(wxList.get(i).getStr("lng"))&&!StrUtil.isEmpty(wxList.get(i).getStr("lat"))){
					//坐标轴正常存在时
					//判断当前距离
					Double mm = LocationUtils.getDistance( Double.valueOf(wxList.get(i).getStr("lat")),Double.valueOf(wxList.get(i).getStr("lng")), lat, lng);
					if(mm>10000){
						
						continue;
					}else{
						wxList.get(i).set("MM", NumberUtil.round(mm, 2));
						retList.add(wxList.get(i));
					}
					;
				}
			}
			if(retList.size()>0){
				Collections.sort(retList, new Comparator<Record>() {  
			        @Override  
			        public int compare(Record c1, Record c2) {  
			            return c1.getDouble("MM").compareTo(c2.getDouble("MM"));  
			        }  
			    });
			}
			return retList;
		}else{
			return null;
		}
	}
	public Double[] getXyByAdd(String add){
		String url = ShopService.GET_ADD_XY.replace("【ADD】", add).replace("【KEY】", ShopService.GET_XY_FORM_KEY);
		String response = sendPostRequest(url);
		if(StrUtil.isEmpty(response)){
			return null;
		}
		Map  resMap= JSONUtil.parseObj(response);
		if((int)resMap.get("status")==0){
			//百度获取坐标成功时
			Map mm = (Map) resMap.get("result");
			Map mmm = (Map) mm.get("location");
			Double[] arr = {(Double) mmm.get("lng"),(Double) mmm.get("lat")};
			return arr;
		}else{
			return null;
		}
	}
	
	public Double getXyFrom(String from,String to){
		Double mm =9999999.00;
		Double [] arr = this.getXyByAdd(to);
		if(arr!=null){
			String url = ShopService.GET_XY_FORM.replace("【FROM】", from).replace("【TO】", arr[1]+","+arr[0]).replace("【KEY】", ShopService.GET_XY_FORM_KEY);
			String response = sendPostRequest(url);
			Map  resMap= JSONUtil.parseObj(response);
			if((int)resMap.get("status")==0){
				//百度获取坐标成功时
				Map mmm = (Map) resMap.get("result");
				JSONArray mmmm = (JSONArray) mmm.get("elements");
				System.out.println(((Map)mmmm.get(0)).get("distance"));
				mm = (Double) ((Map)mmmm.get(0)).get("distance");
			}else{
				
			}
		}
		return mm;
	}
	public Double getXyFrom(String lat,String lng,String to){
		Double mm =9999999.00;
		Double [] arr = this.getXyByAdd(to);
		if(arr!=null){
			mm = LocationUtils.getDistance(arr[1],arr[0], Double.valueOf(lat), Double.valueOf(lng) );
		}else{
			mm=9898989.00;
		}
		return mm;
	}
	
	public String sendPostRequest(String url) {
		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader reader = null;
		HttpURLConnection connection = null;
		try {
			URL postUrl = new URL(url);
			connection = (HttpURLConnection) postUrl.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setReadTimeout(5000);  
			connection.setConnectTimeout(5000); 
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
			stringBuffer.append(line);
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			connection.disconnect();
			if(reader !=null){
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return stringBuffer.toString();
	}
}
